package com.cq.hd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cq.hd.admin.dto.AdminRoleDto;
import com.cq.hd.admin.po.TbAdminRolePo;
import com.cq.hd.admin.mapper.TbAdminRoleMapper;
import com.cq.hd.admin.po.TbAdminUserPo;
import com.cq.hd.admin.service.TbAdminRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cq.hd.admin.service.TbAdminUserService;
import com.cq.hd.admin.vo.AdminRoleVo;
import com.cq.hd.common.enums.biz.DeleteStatusEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.ResultGenerator;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.BeanUtils;
import com.cq.hd.common.utils.LocalDateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2021-10-28
 */
@Service
public class TbAdminRoleServiceImpl extends ServiceImpl<TbAdminRoleMapper, TbAdminRolePo> implements TbAdminRoleService {

    private TbAdminUserService adminUserService;

    @Autowired
    public void setAdminUserService(TbAdminUserService adminUserService) {
        this.adminUserService = adminUserService;
    }

    @Override
    public Page<AdminRoleVo> getAdminRoleList(String name, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<AdminRoleVo> adminRoleVoList = this.baseMapper.listAdminRoleByName(name);

        PageInfo<AdminRoleVo> adminRoleVoPageInfo = new PageInfo<>(adminRoleVoList);
        Page<AdminRoleVo> adminRoleVoPage = new Page<>();
        BeanUtils.copyProperties(adminRoleVoPageInfo, adminRoleVoPage);

        return adminRoleVoPage;
    }

    @Override
    public Object deleteRoleById(Integer id) {
        // 删除角色前查询所有用户是否拥有该角色
        List<TbAdminUserPo> adminUserList = adminUserService.getBaseMapper().selectList(new QueryWrapper<TbAdminUserPo>().
                eq("delete_status", DeleteStatusEnum.NORMAL.getValue())
        );

        if (adminUserList != null && adminUserList.size() > 0) {
            for (TbAdminUserPo adminUser : adminUserList) {
                Integer roleId = adminUser.getRoleId();
                if (roleId.equals(id)) {
                    Throw.isBusinessException("当前角色已关联用户，无法删除!");
                }
            }
        }

        // 根据用户ID物理删除角色
        int delResult = baseMapper.delete(Wrappers.<TbAdminRolePo>lambdaUpdate()
                .eq(TbAdminRolePo::getId, id)
                .eq(TbAdminRolePo::getDeleteStatus, DeleteStatusEnum.NORMAL.getValue()));

        if (delResult == 0) {
            Throw.isBusinessException("角色删除失败");
        }

        return ResultGenerator.success();
    }

    @Override
    public List<TbAdminRolePo> getAllRole() {
        return baseMapper.selectList(new QueryWrapper<TbAdminRolePo>()
                .eq("delete_status", DeleteStatusEnum.NORMAL.getValue())

        );
    }

    @Override
    public void addRole(AdminRoleDto adminRoleDto) {
        adminRoleDto.setCreateTime(LocalDateUtil.getNowLocalDateTime());
        adminRoleDto.setUpdateTime(LocalDateUtil.getNowLocalDateTime());
        baseMapper.insert(adminRoleDto);
    }

    @Override
    public boolean checkExist(String name) {
        Integer countResult = baseMapper.selectCount(new QueryWrapper<TbAdminRolePo>()
                .eq("name", name)
                .eq("delete_status", DeleteStatusEnum.NORMAL.getValue())
        );
        return countResult != 0;
    }

    @Override
    public void updateAdminRoleById(AdminRoleDto adminRoleDto) {
        int updateResult = baseMapper.update(null, Wrappers.<TbAdminRolePo>lambdaUpdate()
                .set(TbAdminRolePo::getUpdateTime, LocalDateUtil.getNowLocalDateTime())
                .set(TbAdminRolePo::getName, adminRoleDto.getName())
                .set(TbAdminRolePo::getRemark, adminRoleDto.getRemark())
                .eq(TbAdminRolePo::getId, adminRoleDto.getId())
                .eq(TbAdminRolePo::getDeleteStatus, DeleteStatusEnum.NORMAL.getValue())
        );
        if (updateResult == 0) {
            throw new RuntimeException("更新数据已失效");
        }
    }

    @Override
    public Set<String> getSetRolesByIds(Integer roleId) {
        Set<String> roles = new HashSet<String>();
        if (roleId == null) {
            return roles;
        }
        List<TbAdminRolePo> roleList = baseMapper.selectList(new QueryWrapper<TbAdminRolePo>()
                .in("id", roleId)
                .eq("enable_status", true)
                .eq("delete_status", DeleteStatusEnum.NORMAL.getValue())
        );
        for (TbAdminRolePo role : roleList) {
            roles.add(role.getName());
        }
        return roles;
    }
}
